package com.demo.crm.security.access.provider;

import com.arvato.crm.common.DynamicQueryUtil;
import com.arvato.crm.model.entity.Permission;
import com.arvato.crm.model.entity.Role;
import com.demo.crm.model.RequestInfo;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 根据请求地址提供授权列表
 *
 * @author tanshuai
 */
@Slf4j
public class ProviderByUrl implements AuthoritiesProvider {

    private static Map<Pattern, Set<String>> patternCaches;

    public Set<String> getAuthorities(RequestInfo requestInfo) {
        Set<String> allows = new HashSet<String>();
        Set<Map.Entry<Pattern, Set<String>>> entries = patternCaches.entrySet();
        for (Map.Entry<Pattern, Set<String>> entry : entries) {
            if (entry.getKey().matcher(requestInfo.getUrl()).matches()) {
                allows.addAll(entry.getValue());
            }
        }
        return allows;
    }

    public ProviderByUrl() {
        loadCaches();
    }

    public static void loadCaches() {
        log.info("加载权限配置缓存");

        List<Permission> permissions = DynamicQueryUtil.getCriteria(Permission.class).leftJoinFetch("roles").getResultList();
        HashMap<Pattern, Set<String>> patternCachesTemp = new HashMap<Pattern, Set<String>>();

        for (Permission permission : permissions) {
            if (StringUtils.isEmpty(permission.getPath())) {
                continue;
            }
            Pattern pattern = Pattern.compile(permission.getPath());

            List<Role> roles = permission.getRoles();
            if (roles != null) {
                HashSet<String> set = new HashSet<String>();
                for (Role role : roles) {
                    set.add(role.getName());
                }
                patternCachesTemp.put(pattern, set);
            }
        }
        patternCaches = patternCachesTemp;
    }
}
